//
//  HomeViewController.swift
//  开心微博
//
//  Created by 郑开心 on 15/12/5.
//  Copyright © 2015年 郑开心. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
import Kingfisher

class HomeViewController: UITableViewController,KXCoverDelegate {
    
    var titleButton : KXTitleButton!
    
    lazy var one : OneTableViewController = {
        let one = OneTableViewController()
        return one
    }()
    
    var task : RetrieveImageTask?
    
    lazy var statusFrames : [StatusFrame] = {
        let statusFrames = [StatusFrame]()
        return statusFrames
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUpNavgationBar()
        self.tableView.backgroundColor = UIColor(colorLiteralRed: 242/255, green: 242/255, blue: 242/255, alpha: 1)
        self.tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        self.tableView.addHeaderWithTarget(self, action: "loadNewStatus")
        self.tableView.headerBeginRefreshing()
        self.tableView.addFooterWithTarget(self, action: "loadMoreStatus")
        
        UserTool.userInfo({
                result in
            self.titleButton.setTitle(result.name, forState: UIControlState.Normal)
            let account = AccountTool.readAccount()
            account?.name = result.name
            AccountTool.saveAccount(account!)
        }, failure: {
                error in debugPrint(error)
        })
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        task?.cancel()
    }
    
    // MARK: -设置NavgationBar
    func setUpNavgationBar(){
        self.navigationItem.leftBarButtonItem = UIBarButtonItem.barButtonItemWithImage(UIImage(named: "navigationbar_friendsearch")!, highImage: UIImage(named: "navigationbar_friendsearch_highlighted")!, target: self, action: "friendsearch",controlEvents: UIControlEvents.TouchUpInside)
        
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.barButtonItemWithImage(UIImage(named: "navigationbar_pop")!, highImage: UIImage(named: "navigationbar_pop_highlighted")!, target: self, action: "pop",controlEvents: UIControlEvents.TouchUpInside)
        
        let titleButton = KXTitleButton(type: UIButtonType.Custom)
        self.titleButton = titleButton
        var title = "首页"
        if let name = AccountTool.readAccount()?.name {
            title = name
        }
        //let title = name!=nil? name:"首页"
        titleButton.setTitle(title, forState: UIControlState.Normal)
        titleButton.setImage(UIImage(named: "navigationbar_arrow_up"), forState: UIControlState.Normal)
        titleButton.setImage(UIImage(named: "navigationbar_arrow_down"), forState: UIControlState.Selected)
        
        titleButton.adjustsImageWhenHighlighted = false
        titleButton.addTarget(self, action: "titleClick:", forControlEvents: UIControlEvents.TouchUpInside)
        self.navigationItem.titleView = titleButton
    }
    
    func friendsearch(){
        //NSLog("\(__FUNCTION__)")
    }
    
    func pop(){
        let popView = TwoViewController()
        //popView.hidesBottomBarWhenPushed = true
        self.navigationController?.pushViewController(popView, animated: true)
    }
    
    func titleClick(btn: UIButton){
        btn.selected = !btn.selected
        
        let cover = KXCover.show()
        cover.delegate = self
        
        let popW : CGFloat = 200
        let popX : CGFloat = (self.view.width - CGFloat(200)) * 0.5
        let popH : CGFloat = popW
        let popY : CGFloat = 55
        let menu = KXPopMenu.showInRect(CGRectMake(popX, popY, popW, popH))
        menu.contentView = self.one.view
    }
    
    func coverDidClickCover(cover: KXCover) {
        KXPopMenu.hide()
        titleButton.selected = false
    }
    
    // MARK: -加载最新微博
    func loadNewStatus(){
        var since_id : String? = nil
        if statusFrames.count > 0{
            let status = statusFrames[0].status
            since_id = status.idstr
        }
        StatusTool.newStatusWithSinceId(since_id,success: {statues in
            
            self.showStatusCount(statues.count)
            self.tableView.headerEndRefreshing()
            
            var statusF = [StatusFrame]()
            for status in statues {
                let statusFrame = StatusFrame()
                statusFrame.status = status
                statusF.append(statusFrame)
            }
            self.statusFrames.insertContentsOf(statusF, at: 0)
            self.tableView.reloadData()
        },failure: {
            error in debugPrint(error)
        })
        
    }
    
    // MARK: -加载更多微博
    func loadMoreStatus(){
        var max_id : String? = nil
        if statusFrames.count > 0{
            max_id = String(Int(statusFrames.last!.status.idstr)! - 1)
        }

        StatusTool.moreStatusWithMaxId(max_id,success: {statues in
            self.tableView.footerEndRefreshing()
            
            var statusF = [StatusFrame]()
            for status in statues {
                let statusFrame = StatusFrame()
                statusFrame.status = status
                statusF.append(statusFrame)
            }
            self.statusFrames.appendContentsOf(statusF )
            self.tableView.reloadData()
        },failure: {
            error in debugPrint(error)
        })
    }
    
    func refresh(){
        self.tableView.headerBeginRefreshing()
    }
    
    // MARK: -加载微博动画
    func showStatusCount(count: Int){
        if count != 0{
            let h : CGFloat = 35
            let y = CGRectGetMaxY(self.navigationController!.navigationBar.frame) - h
            let x : CGFloat = 0
            let w = self.view.width
            let frame = CGRectMake(x, y, w, h)
            let label = UILabel(frame: frame)
            label.backgroundColor = UIColor(patternImage: UIImage(named: "timeline_new_status_background")!)
            label.text = "最新微博数\(count)"
            label.textAlignment = NSTextAlignment.Center
            self.navigationController!.view.insertSubview(label , belowSubview:  self.navigationController!.navigationBar)
            
            UIView.animateWithDuration(0.25, animations: {
                label.transform = CGAffineTransformMakeTranslation(0, h)
                
                }, completion: {finished in
                    UIView.animateWithDuration(0.25, delay: 2, options: UIViewAnimationOptions.CurveLinear, animations: {
                        label.transform = CGAffineTransformIdentity
                        }, completion: {finished in label.removeFromSuperview()})
            })
            
        }
    }

    // MARK: -tabview
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.statusFrames.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //debugPrint("这是第\(indexPath.row+1)行")
        let cell = StatusCell.cellWithTableView(tableView)
        
        let statusFrame = statusFrames[indexPath.row]
        
        cell.statusFrame = statusFrame
        
        
        return cell
    }
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return
            statusFrames[indexPath.row].cellHeight
    }
}
